package com.q.tqb.activity.mine.wallet;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import com.q.tqb.R;
import com.q.tqb.activity.mine.setting.SettingPayPassActivity;
import com.q.tqb.base.AppConst;
import com.q.tqb.base.BaseActivity;
import com.q.tqb.model.MineCardInfo;
import com.q.tqb.util.LogUtil;
import com.q.tqb.util.MD5Util;
import com.q.tqb.util.SPUtil;
import com.q.tqb.util.StringUtil;
import com.q.tqb.util.http.IResponse;
import com.q.tqb.util.http.OkHttpUtil;
import com.q.tqb.view.dialog.PayPassDialog;
import com.tencent.stat.StatService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class WalletWithdrawActivity extends BaseActivity {


    @BindView(R.id.tv_card_type)
    TextView mTvCardType;
    @BindView(R.id.iv_below)
    ImageView mIvBelow;
    @BindView(R.id.et_money)
    EditText mEtMoney;
    @BindView(R.id.tv_mine_money)
    TextView mTvMineMoney;
    @BindView(R.id.tv_add_card)
    TextView mTvAddCard;
    @BindView(R.id.tv_withdraw)
    TextView mTvWithdraw;
    private ArrayList<MineCardInfo> mMineCardInfos;
    private MineCardInfo mMineCardInfo;
    private int uid;
    private String money;
    private String payPassWord;

    @Override
    public int getLayoutId() {
        return R.layout.activity_wallet_withdraw;
    }

    @Override
    public void init(Bundle savedInstanceState) {
        setTitle("提现");
        uid = (int) SPUtil.get(this, "uid", 0);
        money = SPUtil.getString(this, "withdraw");
        payPassWord = SPUtil.getString(this, "payPassword");
        setPayPassDialog();
    }

    private void setPayPassDialog() {

        if (TextUtils.isEmpty(payPassWord)) {
            final AlertDialog.Builder normalDialog = new AlertDialog.Builder(WalletWithdrawActivity.this);
            normalDialog.setTitle("温馨提示");
            normalDialog.setMessage("当前未设置支付密码，无法提现，是否进行设置支付密码?");
            normalDialog.setPositiveButton("确定",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent(WalletWithdrawActivity.this, SettingPayPassActivity.class);
                            startActivityForResult(intent, 50);
                            dialog.dismiss();
                        }
                    });
            normalDialog.setNegativeButton("关闭",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });

            normalDialog.show();
        }

        mTvMineMoney.setText(money);


    }

    private void setCardDialog() {

        final AlertDialog.Builder normalDialog = new AlertDialog.Builder(WalletWithdrawActivity.this);
        normalDialog.setTitle("温馨提示");
        normalDialog.setMessage("当前未添加提现银行卡，无法提现，是否进行添加银行卡?");

        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(WalletWithdrawActivity.this, WalletAddCardActivity.class);
                        startActivityForResult(intent, 51);
                        dialog.dismiss();
                    }
                });

        normalDialog.setNegativeButton("关闭",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

        normalDialog.show();

    }

    @OnClick({R.id.iv_back, R.id.iv_below, R.id.tv_add_card, R.id.tv_withdraw, R.id.tv_card_type})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_below:
            case R.id.tv_card_type:
                showBankDialog();
                break;
            case R.id.tv_add_card:
                Intent intent = new Intent(WalletWithdrawActivity.this, WalletAddCardActivity.class);
                startActivityForResult(intent, 50);
                break;
            case R.id.tv_withdraw:
                withDraw();
                break;
            default:
                break;
        }
    }

    private void withDraw() {
        final String inputMoney = mEtMoney.getText().toString();
        if (TextUtils.isEmpty(payPassWord)) {
            setPayPassDialog();
            return;
        }
        if (inputMoney.isEmpty()) {
            showToast("提现金额不能为零");
            return;
        }

        if (mMineCardInfo == null) {
            showToast("请选择银行卡");
            return;
        }
        final double douInputMoney = Double.valueOf(inputMoney);

        if (douInputMoney < 3) {
            showToast("提现金额须大于3元");
            return;
        }

        double douMoney = Double.valueOf(money);
        if (douInputMoney > douMoney) {
            showToast("余额不足");
            return;
        }

        PayPassDialog payPassDialog = new PayPassDialog(WalletWithdrawActivity.this, douInputMoney, 2);
        payPassDialog.show();
        showInputMethod();
        payPassDialog.setOnSettingListener(new PayPassDialog.CommonListener() {
            @Override
            public void onClick(String pass) {
                mProgressDialog.show();
                Map<String, String> map = new HashMap<>();
                map.put("uid", uid + "");
                map.put("id", mMineCardInfo.getId() + "");
                map.put("money", douInputMoney + "");
                map.put("pay_password", pass);
                map.put("token", StringUtil.getToken(uid));
                LogUtil.i(map.toString());
                OkHttpUtil.getInstance().post(WalletWithdrawActivity.this, AppConst.URL_PAY_MONEY, map, new IResponse() {
                    @Override
                    public void onSuccess(JsonElement element) {
                        mProgressDialog.dismiss();
                        LogUtil.i(element.toString());
                        showToast("提现成功");
                        setResult(RESULT_OK);
                        finish();
                    }

                    @Override
                    public void onFailure(int statusCode, String errorMsg) {
                        mProgressDialog.dismiss();
                        showToast(errorMsg);
                    }
                });
            }

        });
    }

    private void showBankDialog() {
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid + "");
        map.put("token", StringUtil.getToken(uid));
        OkHttpUtil.getInstance().post(WalletWithdrawActivity.this, AppConst.URL_GET_BANK, map, new IResponse() {
            @Override
            public void onSuccess(JsonElement element) {
                LogUtil.i(element.toString());
                Gson gson = new Gson();
                mMineCardInfos  = gson.fromJson(element, new TypeToken<ArrayList<MineCardInfo>>() {
                }.getType());

                if (mMineCardInfos.size() == 0) {
                    setCardDialog();
                } else {
                    final String[] items = new String[mMineCardInfos.size()];
                    for (int i = 0; i < items.length; i++) {
                        String cardNo = mMineCardInfos.get(i).getBank_account();
                        cardNo = StringUtil.formatCard(cardNo);
                        items[i] = mMineCardInfos.get(i).getBank_name() + cardNo;
                    }

                    AlertDialog.Builder listDialog = new AlertDialog.Builder(WalletWithdrawActivity.this);
                    listDialog.setTitle("选择提现卡");
                    listDialog.setItems(items, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            mMineCardInfo = mMineCardInfos.get(which);
                            mTvCardType.setText(String.format("到%s", items[which]));
                            dialog.dismiss();
                        }
                    });
                    listDialog.show();
                }
            }

            @Override
            public void onFailure(int statusCode, String errorMsg) {
                showToast(errorMsg);
            }
        });

    }

    private void showInputMethod() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }, 100);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 50 && resultCode == RESULT_OK) {
            payPassWord = SPUtil.getString(this, "payPassword");
        }

    }
}
